package cn.micro.keep.accounts.service.impl.oss;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.micro.keep.accounts.entity.FileInfo;
import cn.micro.keep.accounts.service.OssService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;

@Component
@ConditionalOnProperty(value = "oss.type", havingValue = "local")
@ConfigurationProperties(prefix = "oss.local")
@RequiredArgsConstructor
@Data
public class LocalOssService implements OssService {

    private String basePath;


    @Override
    public FileInfo uploadFile(MultipartFile file) {
        FileInfo fileInfo = new FileInfo();
        return fileInfo;
    }

    @Override
    public FileInfo uploadFileByUrl(MultipartFile file, String saveUrl) {
        // 生成文件名(日期文件夹)
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        String uuid = IdUtil.simpleUUID();
        String fileName = DateUtil.format(LocalDateTime.now(), "yyyyMMdd") + "/" + uuid + "." + suffix;
        Path path = Paths.get(basePath,saveUrl,fileName);
        File newFile = path.toFile();
        if (!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(newFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileInfo fileInfo = new FileInfo();
        fileInfo.setName(fileName);
        fileInfo.setUrl(path.toString().substring(basePath.length()));
        return fileInfo;
    }

    @Override
    public boolean deleteFile(String filePath) {
        Path path = Paths.get(basePath, filePath);
        File file = path.toFile();
        if (file.exists()){
            return file.delete();
        }
        return false;
    }
}
